﻿using Newtonsoft.Json.Linq;
using System.IO;

namespace EasyNet
{
    public class JSONFile
    {
        string filePath;
        JObject jsonObject;

        public JSONFile(string file_path, JObject json_object)
        {
            filePath = file_path;
            jsonObject = json_object;
        }
        public string GetValueByName(string name_)
        {
            if (File.Exists(filePath))
            {
                string jsonStr = File.ReadAllText(filePath);
                JObject jObject = JObject.Parse(jsonStr);
                if (jObject.ContainsKey(name_))
                {
                    string value = jObject[name_].ToString();
                    return value;
                }
                else
                {
                    return "";
                }
            }
            else
            {
                string jsonStr = jsonObject.ToString();
                File.WriteAllText(filePath, jsonStr);
                return jsonObject[name_].ToString();
            }
        }
        public void SetValueByName(string name_, string value_)
        {
            if (File.Exists(filePath))
            {
                string jsonStr = File.ReadAllText(filePath);
                JObject jObject = JObject.Parse(jsonStr);
                if (jObject.ContainsKey(name_))
                {
                    jObject[name_] = value_;
                }
                else
                {
                    jObject.Add(name_, value_);
                }
                File.WriteAllText(filePath, jObject.ToString());
            }
            else
            {
                string jsonStr = jsonObject.ToString();
                File.WriteAllText(filePath, jsonStr);
            }
        }
        public string FilePath
        {
            get
            {
                return filePath;
            }
            set
            {
                filePath = value;
            }
        }
        public JObject JSONObject
        {
            get
            {
                return jsonObject;
            }
            set
            {
                jsonObject = value;
            }
        }
    }
}
